package org.spring.aicloud.controller.model;

import cn.hutool.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import okhttp3.HttpUrl;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.spring.aicloud.entity.Answer;
import org.spring.aicloud.entity.myenum.AiModelEnum;
import org.spring.aicloud.entity.myenum.AiTypeEnum;
import org.spring.aicloud.service.IAnswerService;
import org.spring.aicloud.util.AppVariable;
import org.spring.aicloud.util.MinioUtil;
import org.spring.aicloud.util.ResponseEntity;
import org.spring.aicloud.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 讯飞大模型
 */
@RestController
@RequestMapping("/xunfei")
@Tag(name = "讯飞大模型")
public class XunfeiController {

    @Value("${xunfei.chat.url}")
    private String chatUrl;
    @Value("${xunfei.chat.api-key}")
    private String chatApiKey;
    @Value("${xunfei.chat.api-secret}")
    private String chatApiSecret;
    @Value("${xunfei.draw.url}")
    private String drawUrl;
    @Value("${xunfei.draw.app-id}")
    private String drawAppId;
    @Value("${xunfei.draw.api-key}")
    private String drawApiKey;
    @Value("${xunfei.draw.api-secret}")
    private String drawApiSecret;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private IAnswerService answerService;
    @Resource
    private MinioUtil minioUtil;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 讯飞的聊天功能
     */
    @RequestMapping("/chat")
    public ResponseEntity chat(String question) throws JsonProcessingException {
        if (!StringUtils.hasLength(question)){
            return ResponseEntity.fail("问题不能为空");
        }
        //在调用接口之前，先针对用户加锁
        //创建key
        String lockKey = AppVariable.getModelLockKey
                (SecurityUtil.getCurrentUser().getUid(),
                        AiModelEnum.XUNFEI.getValue(), AiTypeEnum.CHAT.getValue());
        String content = ""; //大模型返回的结果
        boolean save = false;//数据是否保存成功
        //创建分布式锁实例
        RLock lock = redissonClient.getLock(lockKey);
        boolean isLock = false;
        try {
            isLock = lock.tryLock(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (!isLock) {
            //获取分布式锁失败
            return ResponseEntity.fail("请勿频繁调用接口");
        }
        try {
            String bodyJson = "{\n" +
                    "    \"model\":\"4.0Ultra\",\n" +
                    "    \"messages\": [\n" +
                    "        {\n" +
                    "            \"role\": \"user\",\n" +
                    "            \"content\": \"" + question + "\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}";
            //使用Hutool提供的Http框架发送Http请求
            //要严格按照讯飞提供的文档里的格式来创建请求
            String result = HttpRequest.post(chatUrl)
                    .header("Authorization", "Bearer " + chatApiKey + ":" + chatApiSecret)
                    .header("Content-Type", "application/json")
                    .body(bodyJson)
                    .execute()
                    .body();
            //对返回的Json格式的数据进行解析
            //返回的结果具有固定的格式，在讯飞开放平台的文档中心的HTTP调用文档里查看
            //层层剖析结果，知道拿到其中返回的content
            HashMap<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);
            if (!resultMap.get("code").toString().equals("0")) { //错误的响应
                return ResponseEntity.fail(resultMap.get("message").toString());
            }
            ArrayList list = (ArrayList) resultMap.get("choices");
            LinkedHashMap<String, Object> choices = (LinkedHashMap<String, Object>) list.get(0);
            LinkedHashMap<String, Object> message = (LinkedHashMap<String, Object>) choices.get("message");
            content = message.get("content").toString();
            //将结果保存到数据库当中
            save = answerService.save(Answer.builder()
                    .content(content)
                    .title(question)
                    .type(AiTypeEnum.CHAT.getValue())
                    .model(AiModelEnum.XUNFEI.getValue())
                    .uid(SecurityUtil.getCurrentUser().getUid())
                    .build());
        }catch (Exception ignored){}
        finally {
            //3.释放锁
            lock.unlock();
        }
        if (save){
            return ResponseEntity.success(content);
        }
        return ResponseEntity.fail("操作失败，请重试!");
    }

    /**
     * 调用讯飞大模型聊天的历史信息
     * 此方法不需要参数，关于当前登录的用户信息直接从SpringSecurity中读取即可
     */
    @RequestMapping("/getchatlist")
    public ResponseEntity getChatList(){
        //首先获取到当前的登录用户和调用的大模型
        long uid = SecurityUtil.getCurrentUser().getUid();
        int type = AiTypeEnum.CHAT.getValue();
        int model = AiModelEnum.XUNFEI.getValue();
        //将当前的uid和type和model封装成一个key
        String cacheKey = AppVariable.getListCacheKey(uid,model,type);
        Object value = redisTemplate.opsForValue().get(cacheKey);
        if (value == null){
            QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid",SecurityUtil.getCurrentUser().getUid());
            queryWrapper.eq("type",AiTypeEnum.CHAT.getValue());
            queryWrapper.eq("model",AiModelEnum.XUNFEI.getValue());
            //查询的结果还要按照aid进行倒序排序
            //查询的结果时间是按照最新到最旧的
            queryWrapper.orderByDesc("aid");
            List<Answer> list = answerService.list(queryWrapper);
            //查询到结果之后存储到缓存当中
            redisTemplate.opsForValue().set(cacheKey,list,1,TimeUnit.DAYS );
            //存储完成之后，将查询结果返回
            return ResponseEntity.success(list);
        }else {
            return ResponseEntity.success(value);
        }

    }

    /**
     * 讯飞星火大模型的图片绘画功能
     */
    @RequestMapping("/draw")
    public ResponseEntity draw(String question) throws Exception {
        if (!StringUtils.hasLength(question)){
            return ResponseEntity.fail("问题不能为空");
        }
        //在调用接口之前，先针对用户加锁
        //创建key
        String lockKey = AppVariable.getModelLockKey
                (SecurityUtil.getCurrentUser().getUid(),
                        AiModelEnum.XUNFEI.getValue(), AiTypeEnum.DRAW.getValue());
        String imgUrl = ""; //大模型返回的结果
        boolean save = false;//数据是否保存成功
        //创建分布式锁实例
        RLock lock = redissonClient.getLock(lockKey);
        //尝试获取分布式锁
        boolean isLock = false;
        try {
            isLock = lock.tryLock(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (!isLock) {
            //获取分布式锁失败
            return ResponseEntity.fail("请勿频繁调用接口");
        }
        try {
            //使用httpRequest来进行访问
            //讯飞星火绘画接口访问：Url签名 + 请求体
            //url签名为真正访问的url地址
            //需要通过固定的拼接和加密方式，其中就要用到hostUrl
            String url = getAuthUrl(drawUrl, drawApiKey, drawApiSecret);
            String json = "{\n" +
                    "  \"header\": {\n" +
                    "    \"app_id\": \"" + drawAppId + "\"\n" +
                    "    },\n" +
                    "  \"parameter\": {\n" +
                    "    \"chat\": {\n" +
                    "      \"domain\": \"general\",\n" +
                    "      \"width\": 512,\n" +
                    "      \"height\": 512\n" +
                    "      }\n" +
                    "    },\n" +
                    "  \"payload\": {\n" +
                    "    \"message\": {\n" +
                    "      \"text\": [\n" +
                    "        {\n" +
                    "          \"role\": \"user\",\n" +
                    "          \"content\": \"" + question + "\"\n" +
                    "        }\n" +
                    "      ]\n" +
                    "    }\n" +
                    "  }\n" +
                    "}";
            String result = HttpRequest.post(url)
                    .body(json)
                    .execute()
                    .body();
            //返回的result中的content是基于base64进行编码的
            //Base64是一种编码方法，而不是特定的数据格式。
            // 它是一种将二进制数据转换成文本数据的编码方式，通常用于在网络上以文本形式传输二进制数据。
            //Base64编码会将输入的二进制数据按照固定的算法转换成一种由64个字符组成的可打印ASCII字符串。
            // 因此，在Java中，可以使用Base64.getDecoder()方法将Base64编码的数据解码成原始数据。
            //接下里的任务就是将接受到的result一步步解析出来
            HashMap<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);
            LinkedHashMap<String, Object> payload =
                    (LinkedHashMap<String, Object>) resultMap.get("payload");
            LinkedHashMap<String, Object> choices =
                    (LinkedHashMap<String, Object>) payload.get("choices");
            ArrayList<LinkedHashMap<String, Object>> text =
                    (ArrayList<LinkedHashMap<String, Object>>) choices.get("text");
            LinkedHashMap<String, Object> contentMap = text.get(0);
            //content就是图片的base64编码
            String content = contentMap.get("content").toString();
            //接下来，将base的数据流存储到minio中
            //首先先将base64数据流转换为字节流
            imgUrl = "";
            try (InputStream inputStream =
                         new ByteArrayInputStream(Base64.getDecoder().decode(content))) {
                String imgName = "xf-draw-" + UUID.randomUUID().toString()
                        .replace("-", "");
                imgUrl = minioUtil.upload(imgName, inputStream, "image/png");
            }
            Answer answer = Answer.builder()
                    .model(AiModelEnum.XUNFEI.getValue())
                    .uid(SecurityUtil.getCurrentUser().getUid())
                    .type(AiTypeEnum.DRAW.getValue())
                    .title(question)
                    .content(imgUrl)
                    .build();
            save = answerService.save(answer);
        }catch (Exception ignored){}
        finally {
            //3.释放锁
            lock.unlock();
        }
        if (save){
            return ResponseEntity.success(imgUrl);
        }
        return ResponseEntity.fail("保存失败,请重试!");
    }

    /**
     * 讯飞大模型url签名方法
     * @param hostUrl
     * @param apiKey
     * @param apiSecret
     * @return
     * @throws Exception
     */
    // 鉴权方法
    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // date="Thu, 12 Oct 2023 03:05:28 GMT";
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" + "date: " + date + "\n" + "POST " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        return httpUrl.toString();
    }
    /**
     * 获取讯飞的历史绘画信息
     */
    @RequestMapping("/getdrawlist")
    public ResponseEntity getDrawList() {
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",SecurityUtil.getCurrentUser().getUid());
        queryWrapper.eq("type",AiTypeEnum.DRAW.getValue());
        queryWrapper.eq("model",AiModelEnum.XUNFEI.getValue());
        queryWrapper.orderByDesc("aid");
        List<Answer> answerList = answerService.list(queryWrapper);
        return ResponseEntity.success(answerList);
    }
}

